#!/usr/bin/env python
#-*- coding:utf-8 -*-
''' A sample file '''

import socket

class DNSQuery:
    def __init__(self, data):
        self.data=data
        self.dominio=''
        
        tipo = (ord(data[2]) >> 3) & 15   # Opcode bits
        if tipo == 0:                     # Standard query
          ini=12
          lon=ord(data[ini])              #获取域名DNS请求
          while lon != 0:
            self.dominio+=data[ini+1:ini+lon+1]+'.'
            ini+=lon+1
            lon=ord(data[ini])

    #返回包含IP的DNS数据包
    def respuesta(self, ip):
        packet=''
        if self.dominio:
          packet+=self.data[:2] + "\x81\x80"
          packet+=self.data[4:6] + self.data[4:6] + '\x00\x00\x00\x00'   # Questions and Answers Counts
          packet+=self.data[12:]                                         # Original Domain Name Question
          packet+='\xc0\x0c'                                             # Pointer to domain name
          packet+='\x00\x01\x00\x01\x00\x00\x00\x3c\x00\x04'             # Response type, ttl and resource data length -> 4 bytes
          packet+=str.join('',map(lambda x: chr(int(x)), ip.split('.'))) # 4bytes of IP
        return packet

    #向服务器请求IP
    def request(self):
        self.ip=''
        tmp=''
        print self.dominio
        if self.dominio:
            if self.dominio.startswith('133.199.168.192'):
                return '192.168.199.133'
            if self.dominio.endswith('lan'):
                self.dominio = self.dominio[:self.dominio.rfind('.', 0, len(self.dominio) -1 )]
            try: 
                s=socket.getaddrinfo(self.dominio,None)
                print s
            except: 
                tmp=''
            print s
            tmp=s[0][4][0]
        return tmp


def test():
    ''' Just a Test'''
    server = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
    server.bind(("", 53))
    try:
        while True:
            data, addr = server.recvfrom(1024)
            p=DNSQuery(data)
            ip=p.request()
            server.sendto(p.respuesta(ip), addr)
            print 'Respuesta: %s -> %s' % (p.dominio, ip)
    except KeyboardInterrupt:
        print 'Finalizando'
        server.close()

if __name__  == '__main__':
    test()
